import React, {useState, useEffect} from 'react';
import {View, Text, StyleSheet,ScrollView} from 'react-native';
import AsyncStorage from '@react-native-async-storage/async-storage';
import {connect, ConnectedProps} from 'react-redux';
import {RootState} from '@/models/index';
import Touchable from '../../components/Touchable';
import IconFont from '../../assets/iconfont';
import {windowWidth,getWidth} from "../../utils/index";
import Toast from 'react-native-root-toast';
import {IUserInfo} from '@/models/user';

const mapStateToProps = ({users}: RootState) => {
  return {
    currentUser1:users?.user,
  };
};
const connector = connect(mapStateToProps);
type ModelState = ConnectedProps<typeof connector>;
interface IProps extends ModelState {
  navigation: {navigate: any};
  route: any;
}
const Address = (props: IProps) => {
  const {navigation,currentUser1,dispatch,route} = props;
  useEffect(()=>{
    console.log("currentUser1",currentUser1);
  },[])

  const handleAdd = () => {
    navigation.navigate("AddAddress",{
      user_id:currentUser1 && currentUser1[0]._id ? currentUser1[0]._id : "",
    });
  }
  const handleDelete = (address_id:string) =>{
    console.log("delete");
    dispatch({
      type: 'users/deleteAddress',
      payload: {
        formData: {
          user_id: currentUser1 && currentUser1[0]._id ? currentUser1[0]._id : "",
          address_id:address_id
        },
        callback: () => { 
          dispatch({
            type: 'users/getCurrentUser',
            payload: {
              user_id: currentUser1 && currentUser1[0]._id ? currentUser1[0]._id : "",
              callback: (data:IUserInfo[]) => {   
                data[0] &&   AsyncStorage.setItem('currentUserInfo', JSON.stringify(data[0]));
                Toast.show('删除收货地址成功', {
                  position: Toast.positions.CENTER,
                  duration: Toast.durations.LONG,
                  shadow: true,
                  animation: true,
                });
              },
            },
          });            
        },
      },
    })
  }
  const handleEdit = (item:any) => {
    navigation.navigate("ModifyAddress",{
      user_id:currentUser1 && currentUser1[0]._id ? currentUser1[0]._id : "",
      address:item
    });
  };
  const handleApply = (item:any) => {
    console.log("点击了应用");
    // applyAddress
    dispatch({
      type: 'users/applyAddress',
      payload: {
        formData: {
          user_id: currentUser1 && currentUser1[0]._id ? currentUser1[0]._id : "",
          address_id:item.address_id
        },
        callback: () => { 
          dispatch({
            type: 'users/getCurrentUser',
            payload: {
              user_id: currentUser1 && currentUser1[0]._id ? currentUser1[0]._id : "",
              callback: (data:IUserInfo[]) => {   
                data[0] &&   AsyncStorage.setItem('currentUserInfo', JSON.stringify(data[0]));
                Toast.show('应用收货地址成功', {
                  position: Toast.positions.CENTER,
                  duration: Toast.durations.LONG,
                  shadow: true,
                  animation: true,
                });
              },
            },
          });            
        },
      },
    })
  }
  return (
    <View style={styles.address}>
      <ScrollView>
      <View style={styles.addressBox}>
        {currentUser1 && currentUser1[0].Address && currentUser1[0].Address.length > 0 ? currentUser1[0].Address.map(item => {
          return (
            <View style={styles.addressItem} key={item.address_id}>
              <View style={styles.aTop}>
                <IconFont
                  name="icon-dingwei1"
                  size={30}
                  color={'#A75E5E'}></IconFont>
              </View>
              <View style={styles.aBottom}>
                <View style={styles.bTop}>
                  <Text style={styles.text1}>{item.Consigner_name}</Text>
                  <Text>{item.consigner_phone}</Text>
                </View>
                <Text style={styles.message}>{item.address_message}</Text>
              </View>
              <View style={styles.right}>
                <Touchable onPress={()=>{handleDelete(item.address_id)}}>
                  <IconFont
                    name="icon-shanchu"
                    size={18}
                    color={'#A75E5E'}></IconFont>
                </Touchable>
                <Touchable onPress={()=> {handleEdit(item)}}>
                  <IconFont
                    name="icon-xiugai1"
                    size={18}
                    color={'#A75E5E'}></IconFont>
                </Touchable>
                <Touchable onPress={()=> {handleApply(item)}}>
                  <Text>Apply</Text>
                </Touchable>
              </View>
            </View>
          );
        }) : (
          <Text style={styles.toast}>
            你还没有收货地址，点击下方新增收货地址!!!
          </Text>
        )}
      </View>
      </ScrollView>
      <Touchable style={styles.add} onPress={handleAdd}>
        <Text style={styles.addText}>新增地址</Text>
      </Touchable>
    </View>
  );
};
const styles = StyleSheet.create({
  address: {
    flex: 1,
  },
  addressBox: {
    flex: 1,
    margin:10,
    marginTop:20,
  },
  addressItem:{
    width:"100%",
    paddingVertical:10,
    backgroundColor:"#fff",
    display:"flex",
    flexDirection:"row",
    alignItems:"center",
    borderRadius:5,
    marginVertical:3,
    shadowColor: '#000',
    shadowOffset: {
      width: 5,
      height: 7,
    },
    shadowOpacity: 0.25,
    shadowRadius: 3.84,
    elevation: 5,
  },
  aTop:{
    width:"16%",
    height:45,
    display:"flex",
    justifyContent:"center",
    alignItems:"center"
  },
  aBottom:{
    width:"70%",
    display:"flex"
  },
  bTop:{
    display:"flex",
    flexDirection:"row"
  },
  text1:{
    marginRight:6,
    fontWeight:"700"
  },
  message:{
    paddingVertical:2
  },
  toast: {

  },
  add:{
    width:windowWidth,
    height:90,
    display:"flex",
    justifyContent:"center",
    alignItems:"center",
  },
  addText:{
    width:getWidth(50),
    height:45,
    lineHeight:45,
    color:"#fff",
    fontSize:20,
    textAlign:"center",
    backgroundColor:"#A75E5E",
    borderRadius:30,
  },
  right:{
    width:"14%"
  }
});
export default connector(Address);
